﻿using AutoMapper;
using B.S.BaseData.Api.Read.Command.HospitalCommand;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interface;
using B.S.BataBase.Domain.AI;
using B.S.BataBase.Domain.DTO;
using MediatR;
using Microsoft.AspNetCore.HttpLogging;

namespace B.S.BaseData.Api.Read.CommandHandler.HospitalCommandHandler
{
    public class HistoryOfMedicalVisitsShowCommandHandler : IRequestHandler<HistoryOfMedicalVisitsShowCommand, APIResult<ApiPaging<VisitDTO>>>
    {
        private readonly IBaseRepository<PatientModel> _baseRepository;
        private readonly IBaseRepository<DoctorModel> _doctorbaseRepository;
        private readonly IBaseRepository<VisitTypeModel> _visitTypebaseRepository;
        private readonly IBaseRepository<HistoryOfMedicalVisitsModel> _historyOfMedicalVisitsbaseRepository;
        private readonly IMapper _mapper;
        public HistoryOfMedicalVisitsShowCommandHandler(IBaseRepository<PatientModel> baseRepository, IBaseRepository<DoctorModel> doctorbaseRepository, IBaseRepository<VisitTypeModel> visitTypebaseRepository, IMapper mapper, IBaseRepository<HistoryOfMedicalVisitsModel> historyOfMedicalVisitsbaseRepository)
        {
            _baseRepository = baseRepository;
            _doctorbaseRepository = doctorbaseRepository;
            _visitTypebaseRepository = visitTypebaseRepository;
            _mapper = mapper;
            _historyOfMedicalVisitsbaseRepository = historyOfMedicalVisitsbaseRepository;
        }
        public async Task<APIResult<ApiPaging<VisitDTO>>> Handle(HistoryOfMedicalVisitsShowCommand request, CancellationToken cancellationToken)
        {
            APIResult<ApiPaging<VisitDTO>> result = new APIResult<ApiPaging<VisitDTO>>();
            var list = _historyOfMedicalVisitsbaseRepository.GetAll().Where(x=>x.IsDel==false);
            if (request.Id != null)
            {
                list = list.Where(x => x.VisitPeople == request.Id);
            }
            var res=_mapper.Map<List<VisitDTO>>(list);
            foreach (var item in res)
            {
                item.DoctorName =(await _doctorbaseRepository.GetValues(x=>x.Id==item.VisitDoctor)).DoctorName;
                item.VisitTypeName = (await _visitTypebaseRepository.GetValues(x => x.Id == item.VisitType)).VisitTypeName;
                item.PatientName = (await _baseRepository.GetValues(x => x.Id == item.VisitPeople)).PatientName;
            }
            var totaCount = res.Count();
            var pageCount = (int)Math.Ceiling(totaCount * 1.0 / request.pageSize);
            ApiPaging<VisitDTO> paging = new ApiPaging<VisitDTO>();
            paging.TotalPage = pageCount;
            paging.Total = totaCount;
            paging.PageData = res.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            result.Data = paging;
            result.Code = ApiEnum.Success;
            result.Msg = "就诊信息显示成功";
            return await Task.FromResult(result);
        }
    }
}
